//@author Paulo Mário Andrade
//THESE FUNCTIONS ARE DEPENDANT OF JQUERY, JQUERY UI and VARIABLES CONTAINED IN "view/1_cadastro/signin.tpl"

var statistics_disclaimer_ids = [//not required fields
    "dob", "gender", "school_level", "user_country", "user_state", "user_city"
];
var ssi_disclaimer_ids = [//unusual required fields
    "institution", "institution_start", "institution_end", "institution_country", "institution_state", "institution_city", "source", "classof"
];
var live_study_same_city = $("#live_study_same_city").is(":checked");


$(function() {
    //jquery ui AUTOCOMPLETE STUFF
    activate_autocomplete_fields();

    //AUTO SLASH ON DATE STUFF
    activate_dates_auto_slash();

    //TOOTIP STUFF
    activate_tooltips();

    //LIVE IN THE SAME CITY WHERE STUDIES STUFF
    activate_listeners_for_live_where_studies();

    //email validation
    activate_email_validation();
    //password validation
    activate_password_validation();
    //dates format validation
    activate_dates_validation();
});

function activate_autocomplete_fields() {
    $("#institution").autocomplete({
        source: function(request, response) {
            $.ajax({
                type: 'GET',
                url: URL_ROOT + "cadastro/search_institutions",
                dataType: "json",
                data: {
                    expression: request.term,
                    institution_city: $("#institution_city_id").val()
                },
                success: function(data) {
                    response($.map(data, function(item) {

                        //$("#institution_id").removeClass("ui-autocomplete-loading");
                        $(this).removeClass("ui-autocomplete-loading");
                        return {
                            label: item.acronym + " - " + item.name,
                            value: item.name,
                            id: item.id
                        }
                    }));
                }
            });
        },
        search: function() {
            return this.value;
        },
        focus: function(event, ui) {
            event.preventDefault();
        },
        autoFocus: true,
        selectFirst: true,
        minLength: 0,
        delay: 150,
        select: function(event, ui) {
            $("#institution_id").val(ui.item.id);
        }
    })
            .focus(function() {
        $(this).autocomplete("search", $(this).val());
    });

    $("#classof").autocomplete({
        source: function(request, response) {
            $.ajax({
                type: 'GET',
                url: URL_ROOT + "cadastro/search_classof",
                dataType: "json",
                data: {
                    expression: request.term,
                    institution_id: $("#institution_id").val(),
                    institution_city_id: $("#institution_city_id").val(),
                    institution_start: $("#institution_start").val(),
                    institution_end: $("#institution_end").val()
                },
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            label: item.name,
                            value: item.name,
                            id: item.id
                        }
                    }));
                }
            });
        },
        search: function() {
            return this.value;
        },
        focus: function(event, ui) {
            event.preventDefault();
        },
        autoFocus: true,
        selectFirst: true,
        minLength: 0,
        delay: 150,
        select: function(event, ui) {
            $("#classof_id").val(ui.item.id);
        }
    })
            .focus(function() {
        $(this).autocomplete("search", $(this).val());
    });

    //COUNTRY AUTOCOMPLETE DISABLED UNTIL INTERNATIONAL RELEASE
//     $("#user_country").autocomplete({
//        source: function(request, response) {
//            $.ajax({
//                type: 'GET',
//                url: URL_ROOT + "cadastro/search_countries",
//                dataType: "json",
//                data: {
//                    expression: request.term
//                },
//                success: function(data) {
//                    response($.map(data, function(item) {
//                        return {
//                            label: item.name,
//                            value: item.name,
//                            id: item.id
//                        }
//                    }));
//                }
//            });
//        },
//        search: function() {
//            return this.value;
//        },
//        focus: function(event, ui) {
//            event.preventDefault();
//        },
//        autoFocus: true,
//        selectFirst: true,
//        minLength: 0,
//        delay: 150,
//        select: function(event, ui) {
//            $("#user_country_id").val(ui.item.id);
//        }
//    })
//    .focus(function() {
//        $(this).autocomplete("search", $(this).val());
//    });

    $("#user_state").autocomplete({
        source: function(request, response) {
            $.ajax({
                type: 'GET',
                url: URL_ROOT + "cadastro/search_states",
                dataType: "json",
                data: {
                    expression: request.term
                },
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            label: item.name + " (" + item.acronym + ")",
                            value: item.name,
                            id: item.id

                        }
                    }));
                }
            });
        },
        search: function() {
            return this.value;
        },
        focus: function(event, ui) {
            event.preventDefault();
        },
        autoFocus: true,
        selectFirst: true,
        minLength: 0,
        delay: 150,
        select: function(event, ui) {
            $("#user_state_id").val(ui.item.id);
        }
    })
            .focus(function() {
        $(this).autocomplete("search", $(this).val());
    });

    $("#user_city").autocomplete({
        source: function(request, response) {
            $.ajax({
                type: 'GET',
                url: URL_ROOT + "cadastro/search_cities",
                dataType: "json",
                data: {
                    expression: request.term,
                    state_id: $("#user_state_id").val()
                },
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            label: item.name + " (" + item.acronym + ")",
                            value: item.name,
                            id: item.id

                        }
                    }));
                }
            });
        },
        search: function() {
            return this.value;
        },
        focus: function(event, ui) {
            event.preventDefault();
        },
        autoFocus: true,
        selectFirst: true,
        minLength: 0,
        delay: 150,
        select: function(event, ui) {
            $("#user_city_id").val(ui.item.id);
        }
    })
            .focus(function() {
        $(this).autocomplete("search", $(this).val());
    });

    //COUNTRY AUTOCOMPLETE DISABLED UNTIL INTERNATIONAL RELEASE
//    $("#institution_country").autocomplete({
//        source: function(request, response) {
//            $.ajax({
//                type: 'GET',
//                url: URL_ROOT + "cadastro/search_countries",
//                dataType: "json",
//                data: {
//                    expression: request.term
//                },
//                success: function(data) {
//                    response($.map(data, function(item) {
//                        return {
//                            label: item.name,
//                            value: item.name,
//                            id: item.id
//                            
//                        }
//                    }));
//                }
//            });
//        },
//        search: function() {
//            return this.value;
//        },
//        focus: function(event, ui) {
//            event.preventDefault();
//        },
//        autoFocus: true,
//        selectFirst: true,
//        minLength: 0,
//        delay: 150,
//        select: function(event, ui) {
//            $("#institution_country_id").val(ui.item.id);
//        }
//    })
//    .focus(function() {
//        $(this).autocomplete("search", $(this).val());
//    });

    $("#institution_state").autocomplete({
        source: function(request, response) {
            $.ajax({
                type: 'GET',
                url: URL_ROOT + "cadastro/search_states",
                dataType: "json",
                data: {
                    expression: request.term
                },
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            label: item.name + " (" + item.acronym + ")",
                            value: item.name,
                            id: item.id

                        }
                    }));
                }
            });
        },
        search: function() {
            return this.value;
        },
        focus: function(event, ui) {
            event.preventDefault();
        },
        autoFocus: true,
        selectFirst: true,
        minLength: 0,
        delay: 150,
        select: function(event, ui) {
            $("#institution_state_id").val(ui.item.id);
        }
    })
            .focus(function() {
        $(this).autocomplete("search", $(this).val());
    });

    $("#institution_city").autocomplete({
        source: function(request, response) {
            $.ajax({
                type: 'GET',
                url: URL_ROOT + "cadastro/search_cities",
                dataType: "json",
                data: {
                    expression: request.term,
                    state_id: $("#institution_state_id").val()
                },
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            label: item.name + " (" + item.acronym + ")",
                            value: item.name,
                            id: item.id
                        }
                    }));
                }
            });
        },
        search: function() {
            return this.value;
        },
        focus: function(event, ui) {
            event.preventDefault();
        },
        autoFocus: true,
        selectFirst: true,
        minLength: 0,
        delay: 150,
        select: function(event, ui) {
            $("#institution_city_id").val(ui.item.id);
        }
    })
            .focus(function() {
        $(this).autocomplete("search", $(this).val());
    });


}

function submit_signin_form(form) {
	$('input, option, checkbox, select, button, radio').removeClass("formError");
	$.ajax({
		url: $('#'+form).attr('action'),
		type: 'POST',
		data: $('#'+form).serializeArray(),
		success: function(data){
                    //if the signin was successful, the user will be redirected. Therefore, this sucess function will only be called if there was something wrong with the signin form
                    var obj = JSON.parse(data);
                    for(var i = 0; i<obj.length; i++){
                        $("#"+obj[i]["field"]).addClass("invalid_value");
                    }
                }
	});
	return false;
}

function add3FieldsDateSlashes(input) {
    var v = input.value;
    if (v.match(/^\d{2}$/) !== null) {
        input.value = v + '/';
    } else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
        input.value = v + '/';
    }
}

function add2FieldsDateSlashes(input) {
    var v = input.value;
    if (v.match(/^\d{2}$/) !== null) {
        input.value = v + '/';
    }
}

// Check if string is a valid email address
function activate_email_validation() {
    $("#signin_email, #signin_email_confirm").on('focusout', function() {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if ((re.test($(this).val()) === true)) {
            $(this).removeClass("invalid_value");
        } else {
            $(this).addClass("invalid_value");
            return;
        }
        if (($(this).attr("id") === "signin_email_confirm" && $(this).val() === $("#signin_email").val())) {
            $(this).removeClass("invalid_value");
            return;
        } else if(($(this).attr("id") === "signin_email_confirm" && $(this).val() !== $("#signin_email").val())){
            $(this).addClass("invalid_value");
        }
    });
}

function activate_dates_validation() {
    $("#dob").on('focusout', function() {
        var date = $(this).val().split("/");
        if ($(this).val().match(/^\d{2}\/\d{2}\/\d{2,4}$/) !== null &&
                typeof date[0] != 'undefined' && isNumber(date[0]) && parseInt(date[0]) <= 31 && parseInt(date[0]) > 0 &&
                typeof date[1] != 'undefined' && isNumber(date[1]) && parseInt(date[1]) <= 12 && parseInt(date[1]) > 0 &&
                typeof date[2] != 'undefined' && isNumber(date[2]) && (
                //dob year ranges for 2 or 4 digits input
                        (parseInt(date[2]) <= 04 && parseInt(date[2]) >= 00) ||
                        (parseInt(date[2]) <= 99 && parseInt(date[2]) >= 30) ||
                        (parseInt(date[2]) <= 2004 && parseInt(date[2]) >= 1930)
                        )) {
            $("#dob").removeClass("invalid_value");
        } else {
            $("#dob").addClass("invalid_value");
        }


    });
    $("#institution_start, #institution_end").on('focusout', function() {
        if (check_date_mmyy($(this))) {
            $(this).removeClass("invalid_value");
        } else {
            $(this).addClass("invalid_value");
            return;
        }

        //test if end date is bigger than start date
        if (check_date_mmyy($("#institution_end")) && check_date_mmyy($("#institution_start"))) {
            //a different way to compare dates DD/MM
            var end = $("#institution_end").val().split("/");
            end = parseInt(end[0]) + parseInt(end[1]) * 100;
            var start = $("#institution_start").val().split("/");
            start = parseInt(start[0]) + parseInt(start[1]) * 100;
            if (start > end) {
                alert(START_END_DATE_CONFLICT);
            }
        }
    });
}
function check_date_mmyy(input_field) {
    var date = input_field.val().split("/");
    var curDate = new Date();
    if (input_field.val().match(/^\d{2}\/\d{2,4}$/) !== null &&
            typeof date[0] != 'undefined' && isNumber(date[0]) && parseInt(date[0]) <= 12 && parseInt(date[0]) > 0 &&
            typeof date[1] != 'undefined' && isNumber(date[1]) && (
            //institution start/end year ranges for 2 or 4 digits input: from curyear-10 to curyear+1
                    (parseInt(date[1]) <= curDate.getFullYear() - 2000 + 1 && parseInt(date[1]) >= curDate.getFullYear() - 2000 - 10) ||
                    (parseInt(date[1]) <= curDate.getFullYear() + 1 && parseInt(date[1]) >= curDate.getFullYear() - 10))) {
        return true;

    } else
        return false;
}
function activate_password_validation() {
    $("#account_password, #account_password_confirm").on('focusout', function() {
        if ($(this).val().length < 5) {
            $(this).addClass("invalid_value");
        } else {
            $(this).removeClass("invalid_value");
        }

        if ($(this).attr("id") === "account_password_confirm" && $(this).val() !== $("#account_password").val()) {
            alert(PW_PWCONFIRM_ERROR_MSG);
            $("#account_password").val("");
            $("#account_password_confirm").val("");
        }
    });

}
function activate_dates_auto_slash() {
    $("#dob").on("keyup", function() {
        add3FieldsDateSlashes((this));
    });
    $("#institution_start, #institution_end").on("keyup", function() {
        add2FieldsDateSlashes((this));
    });
}

function activate_tooltips() {
    var i;
    for (i = 0; i < statistics_disclaimer_ids.length; i++) {
        $("#" + statistics_disclaimer_ids[i]).closest("tr").find(".privacy_tooltip1 img").attr("title", STATS_MSG);
    }
    for (i = 0; i < ssi_disclaimer_ids.length; i++) {
        $("#" + ssi_disclaimer_ids[i]).closest("tr").find(".privacy_tooltip1 img").attr("title", SSI_MSG);
    }
    $("input, .required_field, .privacy_tooltip1 img").tooltip({
        content: function() {
            return $(this).attr('title');
        },
        position: {
            at: "right+20 bottom ",
            my: "left center",
        }

    });
}
function  activate_listeners_for_live_where_studies() {
    $("#live_study_same_city").change(function() {
        live_study_same_city = $("#live_study_same_city").is(":checked");
        if (live_study_same_city) {
            $("#institution_country").val($("#user_country").val());
            $("#institution_country_id").val($("#user_country_id").val());
            $("#institution_state").val($("#user_state").val());
            $("#institution_state_id").val($("#user_state_id").val());
            $("#institution_city").val($("#user_city").val());
            $("#institution_city_id").val($("#user_city_id").val());
        }
    });
    $("#user_country").on('change keypress paste focus textInput input', function() {
        if (live_study_same_city) {
            $("#institution_country").val($(this).val());
            $("#institution_country_id").val($("#user_country_id").val());
        }
    });
    $("#user_state").on('change keypress paste focus textInput input', function() {
        if (live_study_same_city) {
            $("#institution_state").val($(this).val());
            $("#institution_state_id").val($("#user_state_id").val());
        }
    });
    $("#user_city").on('change keypress paste focus textInput input', function() {
        if (live_study_same_city) {
            $("#institution_city").val($(this).val());
            $("#institution_city_id").val($("#user_city_id").val());
        }
    });
    $("#institution_country").on('change keypress paste focus textInput input', function() {
        if (live_study_same_city) {
            $("#user_country").val($(this).val());
            $("#user_country_id").val($("#institution_country_id").val());
        }
    });
    $("#institution_state").on('change keypress paste focus textInput input', function() {
        if (live_study_same_city) {
            $("#user_state").val($(this).val());
            $("#user_state_id").val($("#institution_state_id").val());
        }
    });
    $("#institution_city").on('change keypress paste focus textInput input', function() {
        if (live_study_same_city) {
            $("#user_city").val($(this).val());
            $("#user_city_id").val($("#institution_city_id").val());
        }
    });

}